package com.aispeech.testcustom.utils;

import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;

import com.aispeech.testcustom.TiApplication;
import com.aispeech.testcustom.bean.Command;
import com.aispeech.testcustom.i.GetDataFromXml;
import com.aispeech.testcustom.i.TiConst;
import com.aispeech.testcustom.i.XcallBack;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * Created by rain on 2016/11/6.
 */
public class AssetsUtils {
    /**
     * 读取初始化配置文件
     *
     * @param pathAndName
     * @param key
     * @param defaultValue
     * @return
     */
    public static String readProperties(String pathAndName, String key, String defaultValue) {
        /**
         * asti_custom : 测试自定义指令
         * 默认所有文件push 到/sdcard根目录
         * android6.0等后面再说
         */
        if (TextUtils.isEmpty(pathAndName)) {
            pathAndName = File.separator + "sdcard" + File.separator
                    + "asti_custom.txt";
        }

        String value = null;
        try {
            Log.d("test", "pachAndName:" + pathAndName);
            File file = new File(pathAndName);
            if (file.isFile() && file.canRead()) {
                InputStream inputStream = new FileInputStream(file);
                Properties properties = new Properties();

                properties.load(inputStream);
                value = properties.getProperty(key);
                inputStream.close();

                return TextUtils.isEmpty(value) ? defaultValue : new String(value.getBytes
                        ("ISO-8859-1"), "utf-8");
            } else {
                //文件不存在或者没有配置正确
                return "nofile";
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return TextUtils.isEmpty(value) ? defaultValue : value;
    }


    static List<Command> list = null;
    static Command       cmd  = null;
    static String[]      scmd = null;
    static StringBuffer  sb   = new StringBuffer();
    ;

    /**
     * 将现有list转成register所需要的格式
     * List<Command> mlist
     */
    public static List<com.aispeech.aios.sdk.bean.Command> convertList4Register(List<Command>
                                                                                        mlist) {
        List<com.aispeech.aios.sdk.bean.Command> list = new ArrayList<>();
        String[] s = null;
        com.aispeech.aios.sdk.bean.Command sdkCommand = null;
        if (mlist.size() > 0) {
            for (Command c : mlist) {
                List<Command.CmdItem> keywords = c.getKeywords();
                if (keywords.size() > 0) {
                    s = new String[keywords.size()];
                    for (int i = 0; i < keywords.size(); i++) {
                        s[i] = keywords.get(i).getCmd();
                    }
                }
                sdkCommand = new com.aispeech.aios.sdk
                        .bean.Command(c.getCommand(), s);
                list.add(sdkCommand);

            }
        }
        return list;
    }

    /**
     * pull解析读取自定义指令
     * 默认读取目录/sdcard/custom_cmd.xml
     */
    public static void readCommandFormXML(String path, final GetDataFromXml getDataFromXml) {


        if (TextUtils.isEmpty(path)) {
            //读取sd卡根目录下文件
            path = File.separator + "sdcard" + File.separator + "custom_cmd.xml";
        }

        final FileInputStream fin;
        try {
            fin = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            TiLog.d("readCommandFormXML: FileNotFoundException");
            e.printStackTrace();
            getDataFromXml.fail(TiConst.IO_ERROR);
            return;
        }
        if (null == fin) {
            TiLog.d("readCommandFormXML: FileInputStream is null");
            getDataFromXml.fail(TiConst.PATH_ERROR);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    XmlPullParser parser = Xml.newPullParser();
                    parser.setInput(fin, "UTF-8");

                    int eventType = parser.getEventType();
                    while (eventType != XmlPullParser.END_DOCUMENT) {
                        //                        String name = parser.getName();
                        switch (eventType) {

                            case XmlPullParser.START_DOCUMENT:
                                list = new ArrayList<Command>();
                                break;
                            case XmlPullParser.START_TAG:
                                if (parser.getName().equals("url")) {
                                    cmd = new Command();
                                    cmd.setCommand(parser.getAttributeValue(0));
                                } else if (parser.getName().equals("cmd")) {
                                    sb.append(parser.getAttributeValue(0) + ",");
                                }
                                break;
                            case XmlPullParser.END_TAG:
                                if (parser.getName().equals("url")) {
                                    scmd = sb.toString().split(",");
                                    cmd.setKeywords(scmd);
                                    list.add(cmd);
                                    sb.delete(0, sb.length());
                                    scmd = null;
                                    cmd = null;
                                }
                                break;
                        }
                        eventType = parser.next();
                    }

                    getDataFromXml.success(list);
                } catch (XmlPullParserException e) {
                    TiLog.e("XmlPullParserException ERROR");
                    e.printStackTrace();
                    getDataFromXml.fail(TiConst.PARSER_ERROR);
                } catch (IOException e) {
                    TiLog.e("IOException ERROR");
                    e.printStackTrace();
                    getDataFromXml.fail(TiConst.IO_ERROR);
                }
            }
        }).start();
    }

    /**
     * 将识别结果写入本地
     *
     * @param path
     * @param result 默认输出路径为context.getExternalCacheDir()
     */
    public static void printRusult(String path, List<Command> result, XcallBack xcallBack) {
        if (TextUtils.isEmpty(path)) {
            if (SystemUtils.getExternalCacheDir(TiApplication.getContext()) == null) {
                //无法写文件
                TiLog.d("SaveWavFileFromWakeup: cannot getExternalCacheDir");
                return;
            }
            //            path = SystemUtils.getExternalCacheDir(TiApplication.getContext())
            // .getAbsolutePath();
            path = File.separator + "sdcard" + File.separator + "custom_cmd_result.txt";

            TiLog.d("文件导出路径: " + path);
        }

        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            FileOutputStream out = new FileOutputStream(file);
            OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
            BufferedWriter bufWrite = new BufferedWriter(outWriter);
            for (int i = 0; i < result.size(); i++) {
                Command command = result.get(i);
                String c = command.getCommand();
                bufWrite.write(c + "\r\n");
                List<Command.CmdItem> keywords = command.getKeywords();

                for (int j = 0; j < keywords.size(); j++) {
                    Command.CmdItem cmdItem = keywords.get(j);

                    bufWrite.write("\t" + cmdItem.getCmd() + "\t\t\t->" + cmdItem.isCheckResult() +
                            "\r\n");
                }
            }

            bufWrite.close();
            outWriter.close();
            out.close();

            xcallBack.success();
        } catch (IOException e) {
            e.printStackTrace();
            xcallBack.fail();
        }
    }

    public static void printRusultExcel(String path, List<Command> result, XcallBack xcallBack,
                                        String docname, String title) {
        if (TextUtils.isEmpty(path)) {

            if (SystemUtils.getExternalCacheDir(TiApplication.getContext()) == null) {
                //无法写文件
                TiLog.d("SaveWavFileFromWakeup: cannot getExternalCacheDir");
                return;
            }
            //            path = SystemUtils.getExternalCacheDir(TiApplication.getContext())
            // .getAbsolutePath();
            path = File.separator + "sdcard" + File.separator + docname;
            TiLog.d("文件导出路径: " + path);
        }

        try {
            File file = new File(path);
            WritableWorkbook workbook = Workbook.createWorkbook(file);
            //创建excel工作表
            WritableSheet sheet = workbook.createSheet(docname, 0);//custom_cmd_result
            //设置单元格字体
            WritableFont TitleFont = new WritableFont(WritableFont.ARIAL, 14);
            WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 12);
            WritableFont RedFont = new WritableFont(WritableFont.ARIAL, 12,WritableFont.NO_BOLD,
                    false, UnderlineStyle.NO_UNDERLINE, Colour.RED);

            // 用于标题居中
            WritableCellFormat wcf_Title = new WritableCellFormat(TitleFont);
            wcf_Title.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
            wcf_Title.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_Title.setAlignment(Alignment.CENTRE); // 文字水平对齐
            wcf_Title.setWrap(false); // 文字是否换行

            // 用于正文居中
            WritableCellFormat wcf_center = new WritableCellFormat(NormalFont);
            wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
            wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
            wcf_center.setWrap(false); // 文字是否换行

            //红色字体,用于标出
            WritableCellFormat wcf_mark = new WritableCellFormat(RedFont);
            wcf_mark.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
            wcf_mark.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_mark.setAlignment(Alignment.CENTRE); // 文字水平对齐
            wcf_mark.setWrap(false); // 文字是否换行


            //第一行标题
            sheet.mergeCells(0, 0, 2, 0);
            sheet.addCell(new Label(0, 0, title, wcf_Title));


            //先写死了, 后面有时间再单独抽取出来
            sheet.addCell(new Label(0, 1, "测试Url", wcf_center));
            sheet.addCell(new Label(1, 1, "测试指令", wcf_center));
            sheet.addCell(new Label(2, 1, "测试结果", wcf_center));

            //            Field[] fields = null;

            int m = 0;
            for (int i = 0; i < result.size(); i++) {
                //设置列的宽度(哪列, 宽度数字)
                sheet.setColumnView(i, 50);

                Command command = result.get(i);
                String c = command.getCommand();

                if (m==0){
                    //第一行不空行
                    sheet.addCell(new Label(0, i + 2 + m, c, wcf_center));
                }else{
                    sheet.addCell(new Label(0, i + 2 + m + 1, c, wcf_center));
                }

                List<Command.CmdItem> keywords = command.getKeywords();

                int j = 0;
                for (; j < keywords.size(); j++) {
                    Command.CmdItem cmdItem = keywords.get(j);
                    sheet.addCell(new Label(1, j + 3 + i + m, cmdItem.getCmd(), wcf_center));
                    sheet.addCell(new Label(2, j + 3 + i + m, "" + cmdItem.isCheckResult(),
                            cmdItem.isCheckResult() ? wcf_center : wcf_mark));

                }
                m += j;


            }
            //写到excel中
            workbook.write();
            workbook.close();

            xcallBack.success();


        } catch (Exception e) {
            TiLog.e("printExcel error!!!");
            xcallBack.fail();
            e.printStackTrace();
        }
    }

}
